﻿using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using Tools.Debugging;

namespace repliback4.Net.ServerSide {

    public class ServerConnection : AsyncConnection {
        protected ServerSide.Client servClient;
        public ServerConnection ( ServerSide.Client servClient, TcpClient client )
            : base( client ) {
            this.servClient = servClient;
        }

        public void SwitchToSecure ( ) {

            //this.netStream = new SslStream( this.netStream, true, new RemoteCertificateValidationCallback( this.RemoteCertificateValidationCallback ), new LocalCertificateSelectionCallback( this.LocalCertificateSelectionCallback ) );
            this.sslStream = new SslStream( this.netStream );
            X509Certificate x = new X509Certificate( "mypkccert.p12", "" );

            this.sslStream.AuthenticateAsServer( x, false, System.Security.Authentication.SslProtocols.Tls, true );
            this.stream = this.sslStream;



        }

        public Boolean TrySwitchToSecure ( ) {

            try {
                this.SwitchToSecure( );
                return true;
            } catch ( AuthenticationException e ) {
                Logger.Exception( this, "Switching to secure: AuthenticationException:", e );
            } catch ( Exception e ) {
                Logger.Exception( this, "Switching to secure: Exception:", e );
            }
            return false;
        }

        //protected bool RemoteCertificateValidationCallback ( object o, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors ) {
        //    Logger.DebugFormat( this, "RemoteCertificateValidationCallback\n\tobj: {0}\n\tcertificate: {1}\n\tchain: {2}\n\terror: {3}", o, certificate, chain, errors );
        //    return true;
        //}
        //protected X509Certificate LocalCertificateSelectionCallback ( Object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers ) {
        //    //new LocalCertificateSelectionCallback();
        //    Logger.DebugFormat( this, "LocalCertificateSelectionCallback\n\tsender: {0}\n\ttargetHost: {1}\n\tlocalCertificates: {2}\n\tremoteCertificate: {3}\n\tacceptableIssuers: {4}", sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers );
        //    return localCertificates[0];
        //}
    }
}